package com.example.demo.xml.handler;


import com.example.demo.model.User;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.springframework.beans.factory.xml.NamespaceHandlerSupport;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;

/**
 * @author yujie
 * @create 2018-04-26 下午5:58
 **/
public class PeopleNamespaceHandler extends NamespaceHandlerSupport {

    @Override
    public void init() {
        registerBeanDefinitionParser("user", new PeopleBeanDefinitionParser());
    }

    public class PeopleBeanDefinitionParser extends AbstractSingleBeanDefinitionParser {


        @Override
        protected Class<?> getBeanClass(Element element) {
            /**
             * 返回类型
             */
            return User.class;
        }

        @Override
        protected void doParse(Element element, BeanDefinitionBuilder bean) {
            /**
             * 解析xml
             */
            String name = element.getAttribute("name");
            String age = element.getAttribute("age");
            String id = element.getAttribute("id");
            if (StringUtils.hasText(id)) {
                bean.addPropertyValue("id", id);
            }
            if (StringUtils.hasText(name)) {
                bean.addPropertyValue("name", name);
            }
            if (StringUtils.hasText(age)) {
                bean.addPropertyValue("age", Integer.valueOf(age));
            }
        }

    }
}
